<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iostat Log to ECharts</title>
    <!-- 引入ECharts -->
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.3.3/echarts.min.js"></script>
    <style>
        #chart {
            width: 100%;
            height: 600px;
        }
        .controls {
            margin-bottom: 20px;
        }
        .controls label {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1 id="chartTitle">iostat Log to ECharts</h1>
    <div class="controls">
        <input type="file" id="fileInput" accept=".log,.txt">
        <div id="columnSelect"></div>
    </div>
    <div id="chart"></div>

    <script>
        let chart = null;
        let baseTime = null;
        let logData = [];
        const defaultColumns = ['rkB/s', 'wkB/s', 'aqu-sz', '%util'];

        // 初始化 ECharts
        function initChart() {
            const chartDom = document.getElementById('chart');
            chart = echarts.init(chartDom);
            chart.setOption({
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: defaultColumns
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        formatter: function (value) {
                            return new Date(value).toLocaleTimeString();
                        },
                        interval: 60 * 1000 // 每隔1分钟显示一个标签
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        interval: 1000
                    }
                },
                dataZoom: [{
                    show: true,
                    realtime: true,
                    start: 0,
                    end: 10,
                    xAxisIndex: [0, 1]
                }],
                series: defaultColumns.map(col => ({
                    data: [],
                    name: col,
                    type: 'line',
                    lineStyle: {
                    width: 1 // 设置线条宽度为5像素
                    }
                }))
            });
        }

        // 从文件名中提取 IP 地址和时间
        function parseFileName(filename) {
            const regex = /^(.*?)_(\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2})\.log$/;
            const match = filename.match(regex);
            if (match) {
                const ip = match[1];
                const timeStr = match[2].replace(/_/g, ':');
                baseTime = new Date(timeStr).getTime();
                document.getElementById('chartTitle').innerText = `iostat Log for IP: ${ip}`;
            } else {
                baseTime = new Date().getTime();
                document.getElementById('chartTitle').innerText = 'iostat Log to ECharts';
            }
        }

        // 解析日志文件
        function parseLog(file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                const content = e.target.result;
                const lines = content.split('\n');
                let headersIndex = -1;

                // 找到以 'Device' 开头的行作为真正的首行数据
                for (let i = 0; i < lines.length; i++) {
                    if (lines[i].trim().startsWith('Device')) {
                        headersIndex = i;
                        break;
                    }
                }

                if (headersIndex === -1) {
                    console.error('No header line found starting with "Device".');
                    return;
                }

                const headers = lines[headersIndex].trim().split(/\s+/);
                logData = [];
                console.log(lines.length);

                // 从找到的首行数据的下一行开始解析数据
                for (let i = headersIndex + 1; i < lines.length; i += 4) {
                    const dataLine = lines[i].trim().split(/\s+/);
                    if (dataLine.length === headers.length) {
                        const dataObj = { id: logData.length + 1 };
                        headers.forEach((header, index) => {
                            if (header !== 'Device') {
                                dataObj[header] = parseFloat(dataLine[index]);
                            }
                        });
                        dataObj.timestamp = baseTime + dataObj.id * 10 * 1000; // 每10秒一个时间戳
                        logData.push(dataObj);
                        console.log(dataObj);
                    }
                }

                updateChart(defaultColumns);
                updateColumnSelect(headers.filter(h => h !== 'Device'));
            };
            reader.readAsText(file);
        }

        // 更新图表
        function updateChart(columns) {
            const xAxisData = logData.map(d => d.timestamp);
            const series = columns.map(col => ({
                name: col,
                type: 'line',
                data: logData.map(d => [d.timestamp, d[col]])
            }));

            chart.setOption({
                xAxis: {
                    data: xAxisData
                },
                series: series,
                legend: {
                    data: columns
                }
            });
        }

        // 更新列选择器
        function updateColumnSelect(columns) {
            const columnSelect = document.getElementById('columnSelect');
            columnSelect.innerHTML = columns.map(col => `
                <label>
                    <input type="checkbox" value="${col}" ${defaultColumns.includes(col) ? 'checked' : ''}>
                    ${col}
                </label>
            `).join('');

            columnSelect.querySelectorAll('input').forEach(input => {
                input.addEventListener('change', () => {
                    const selectedColumns = Array.from(columnSelect.querySelectorAll('input:checked')).map(i => i.value);
                    updateChart(selectedColumns);
                });
            });
        }

        // 文件选择事件
        document.getElementById('fileInput').addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (file) {
                parseFileName(file.name);
                parseLog(file);
            }
        });

        // 初始化
        initChart();
    </script>
</body>
</html>